package com.bawei.home.view

import android.util.Log
import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.base.RoutePath
import com.bawei.common.entity.SimpleVideoEntity
import com.bawei.common.event.LiveDataBus
import com.bawei.common.event.LiveDataBusEvent
import com.bawei.common.mvi.BaseMviFragment
import com.bawei.home.R
import com.bawei.home.adapter.HomeVideoListAdapter
import com.bawei.home.databinding.FragmentHomeListBinding
import com.bawei.home.intent.HomeViewIntent
import com.bawei.home.uistate.HomeUiState
import com.bawei.home.viewmodel.HomeViewModel
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = RoutePath.PATH_FRAGMENT_HOME_LIST)
class HomeListFragment : BaseMviFragment<FragmentHomeListBinding>() {

    private val mViewModel: HomeViewModel by activityViewModels()

    @Autowired
    @JvmField
    var typeId: Int = -1
    @Autowired
    @JvmField
    var channelId: String = ""

    private var pageIndex = 1
    private var pageSize = 10
    private var simpleVideoList = mutableListOf<SimpleVideoEntity>()
    private lateinit var mRecyclerView: RecyclerView
    private lateinit var mVideoListAdapter: HomeVideoListAdapter

    override fun getLayoutId(): Int = R.layout.fragment_home_list

    override fun initViews() {
        ARouter.getInstance().inject(this)

        //列表下拉刷新
        mDataBinding.refreshLayout.setOnRefreshListener {
            pageIndex = 1
            refreshOrMoreList()
        }

        //获取RecyclerView，并进行优化
        mRecyclerView = mDataBinding.rvHomeList
        mRecyclerView.setHasFixedSize(true) //固定的ItemView大小
        mRecyclerView.isNestedScrollingEnabled = false //嵌套禁止滚动
        mRecyclerView.setItemViewCacheSize(20) //缓存ItemView的数量

        //创建缓存池
        var cachePool = RecyclerView.RecycledViewPool().apply {
            setMaxRecycledViews(0, 5) //ViewType类型必须和数据适配器中ItemType一致
        }
        mRecyclerView.setRecycledViewPool(cachePool)

        //设置页面中图片在滚动时暂停加载
        mRecyclerView.addOnScrollListener(object : OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE){
                    Glide.with(this@HomeListFragment).resumeRequests()
                }else{
                    Glide.with(this@HomeListFragment).pauseRequests()
                }
            }
        })

        //取消不需要的动画
        (mRecyclerView.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

        mVideoListAdapter = HomeVideoListAdapter(simpleVideoList)
        mVideoListAdapter.apply {
            preloadEndCount = 4
            preloadData = {
                pageIndex += 1
                refreshOrMoreList()
            }
        }

        //设置适配器点击事件
        mVideoListAdapter.setOnItemClickListener(object : HomeVideoListAdapter.OnItemClickListener{
            override fun onItemClick(v: View, position: Int) {
                when(v.id){
                    R.id.iv_video_play -> {
                        ARouter.getInstance().build(RoutePath.PATH_PLAY_PAGE).withInt("typeId", typeId).withString("channelId", channelId).withSerializable("videoEntity", simpleVideoList[position]).navigation()
                    }
                    R.id.iv_commend -> {
                        LiveDataBus.with<LiveDataBusEvent>("video_options").value = LiveDataBusEvent(100, simpleVideoList[position])
                    }
                    R.id.iv_more -> {
                        LiveDataBus.with<LiveDataBusEvent>("video_options").value = LiveDataBusEvent(101, simpleVideoList[position])
                    }
                }
            }
        })

        mRecyclerView.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        mRecyclerView.swapAdapter(mVideoListAdapter, true) //可以开启屏幕外View的缓存

    }


    private fun refreshOrMoreList(){
        lifecycleScope.launch {
            if (typeId == -1){
                mViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideoList(pageIndex, pageSize))
            } else {
                mViewModel.channel.send(HomeViewIntent.LoadSimpleVideoListById(channelId, pageIndex, pageSize))
            }
        }
    }

    override suspend fun sendViewIntent() {
//        if (typeId == -1){
//            mViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideoList(pageIndex, pageSize))
//        } else {
//            mViewModel.channel.send(HomeViewIntent.LoadSimpleVideoListById(channelId, pageIndex, pageSize))
//        }
    }

    private fun lazyLoadData(){
        //执行新数据加载
        lifecycleScope.launch {
            if (typeId == -1){
                mViewModel.channel.send(HomeViewIntent.LoadRecommendSimpleVideoList(pageIndex, pageSize))
            } else {
                mViewModel.channel.send(HomeViewIntent.LoadSimpleVideoListById(channelId, pageIndex, pageSize))
            }
        }
    }

    override fun onResume() {
        super.onResume()
        lazyLoadData()
    }

    override suspend fun collectUiState() {
        mViewModel.uiState.collect{
            when(it){
                is HomeUiState.LoadSimpleVideoSuccess -> updatePageData(it.list)
                is HomeUiState.LoadSimpleVideoFail -> {
                    if (pageIndex > 1){
                        pageIndex -= 1
                    }
                    if(simpleVideoList.size > 0){
                        simpleVideoList.clear()
                        mVideoListAdapter.notifyDataSetChanged()
                    }
                    showToastMsg(it.msg)
                }
                else -> {}
            }
        }
    }

    private fun updatePageData(list: List<SimpleVideoEntity>) {
        if(pageIndex == 1){
            mDataBinding.refreshLayout.finishRefresh()
            simpleVideoList.clear()
        }

        //使用DiffUtil计算增量数据，提高刷新效率（与ViewPager2使用时，因为缓存到时数组大小不一致问题）
//        val diffCallback = ItemDiffCallback(simpleVideoList, list)
//        val diffResult = DiffUtil.calculateDiff(diffCallback)
        simpleVideoList.addAll(list)

        //分发给数据适配器刷新页面
//        diffResult.dispatchUpdatesTo(mVideoListAdapter)

        Log.i("======", "updatePageData: ${list.size} , typeId=${typeId}")

        //传统全量刷新
        mRecyclerView.adapter = mVideoListAdapter
        mVideoListAdapter.notifyDataSetChanged()


    }



}